const express = require('express');
const axios = require('axios');
const cors = require('cors');

const app = express();
const port = 3000;

const AK = "qjHvSw0fW3yPUpoY71h5G0BX"; // 百度 API Key
const SK = "aafDR2bk6JhGPODnVp48RoKM5RnI7uwN"; // 百度 Secret Key

app.use(cors());
app.use(express.json());

async function getAccessToken() {
    try {
        const response = await axios.post(
            `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${AK}&client_secret=${SK}`
        );
        return response.data.access_token;
    } catch (error) {
        console.error('获取百度 API 访问令牌失败:', error.message);
        throw error;
    }
}

async function askBaiduAPI(question) {
    try {
        const token = await getAccessToken();
        const response = await axios.post(
            `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=${token}`,
            { messages: [{ role: "user", content: question }] },
            { headers: { 'Content-Type': 'application/json' } }
        );

        if (response.data && response.data.result) {
            return response.data.result;
        } else {
            return "未能获取到回答";
        }
    } catch (error) {
        console.error('百度 API 请求失败:', error.message);
        throw error;
    }
}

app.post('/ask', async (req, res) => {
    const { question } = req.body;

    if (!question) {
        return res.status(400).json({ error: "问题不能为空" });
    }

    try {
        const answer = await askBaiduAPI(question);
        return res.json({ answer });
    } catch (error) {
        console.error('服务器错误:', error.message);
        return res.status(500).json({ error: '服务器错误，请稍后再试' });
    }
});

app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
});